package com.wishwall.utils;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.wishwall.exceptions.WishWallException;

public class Utils {

	/**
	 *
	 * @param inputList
	 * @return
	 */
	public static <T> List<T> copyListElementsByValue(List<T> inputList) {
		List<T> returnList = new ArrayList<T>();
		if(inputList != null) {
			returnList.addAll(inputList);
		}
		return returnList;
	}

	/**
	 *
	 * @param objDest
	 * @param objSource
	 * @param propsToExclude
	 * @throws ImmediateException
	 */
	public static void copyProperties(Object objDest, Object objSource, String... propsToExclude)
			throws WishWallException {

		if (objDest == null || objSource == null || propsToExclude == null) {
			return;
		}

		HashSet<String> excludes = new HashSet<String>();
		excludes.add("class");
		excludes.addAll(Arrays.asList(propsToExclude));
		PropertyDescriptor[] descriptorsList = PropertyUtils
				.getPropertyDescriptors(objDest);
		try {
			for (PropertyDescriptor descriptor : descriptorsList) {
				if (excludes.contains(descriptor.getName())
						|| PropertyUtils.getPropertyDescriptor(objSource,
								descriptor.getName()) == null) {
					continue;
				}
				Object value = PropertyUtils.getProperty(objSource,
						descriptor.getName());

				BeanUtils.copyProperty(objDest, descriptor.getName(), value);
			}
		} catch (Exception e) {
			throw new WishWallException(e);
		}
	}

	public static void copyPropertiesIfNotNull(Object objDest, Object objSource, String... propsToExclude)
			throws WishWallException {

		if (objDest == null || objSource == null || propsToExclude == null) {
			return;
		}

		HashSet<String> excludes = new HashSet<String>();
		excludes.add("class");
		excludes.addAll(Arrays.asList(propsToExclude));
		PropertyDescriptor[] descriptorsList = PropertyUtils
				.getPropertyDescriptors(objDest);
		try {
			for (PropertyDescriptor descriptor : descriptorsList) {
				if (excludes.contains(descriptor.getName())
						|| PropertyUtils.getPropertyDescriptor(objSource,
								descriptor.getName()) == null) {
					continue;
				}
				Object value = PropertyUtils.getProperty(objSource,
						descriptor.getName());

				if (value != null) {
					BeanUtils.copyProperty(objDest, descriptor.getName(), value);
				}
			}
		} catch (Exception e) {
			throw new WishWallException(e);
		}
	}

}
